package com.zsc.wxm.ysh.anjo.es.crawler;

import com.zsc.wxm.ysh.anjo.service.base.constant.CrawlerConstant;
import com.zsc.wxm.ysh.anjo.service.base.constant.OtherConstant;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Html;

import java.util.List;

/**
 * 描述： 数据爬虫
 *
 * @author playmaker
 * @since 2021/2/13 21:59
 */
public class DataCrawlerProcessor implements PageProcessor {

    /**
     * 获取数据的渠道
     */
    private String channelUrl = "";

    /**
     * 抓取网站的相关配置，包括编码、抓取间隔、重试次数等
     */
    private Site site = Site.me().setRetryTimes(3).setSleepTime(1000).setTimeOut(10000);

    /**
     * process是定制爬虫逻辑的核心接口，在这里编写抽取逻辑
     * @param page
     */
    @Override
    public void process(Page page) {
        Html html = page.getHtml();
        //获取title body > div.wrapper > div:nth-child(2) > div.content.clear.w1150
        List<String> list = html.css(".content__list--item--title a").links().all();
        page.addTargetRequests(list);
        String title = html.xpath("//div[@class='content clear w1150']/p/text()").toString();
        page.putField("title", title);
        //租金content_article_table  #aside > ul  //p[@class='content__aside--title']/span/text()
        page.putField("rent", html.xpath("//div[@class='content__aside--title']/span/text()").toString());
        page.putField("type", html.xpath("//ul[@class='content__aside__list']/allText()").toString());
        page.putField("info", html.xpath("//div[@class='content__article__info']/allText()").toString());
        page.putField("img", html.xpath("//div[@class='content__article__slide__item']/img").toString());
        page.putField("houseDesc",html.xpath("//div[@class='content__article__info3']/p/text()").toString());
        page.putField("code",html.xpath("//i[@class='house_code']/text()").toString());
        if (page.getResultItems().get("title") == null) {
            //详情页跳过
            page.setSkip(true);
            //分页链接
            for (int i = 1; i <= OtherConstant.GET_DATA_PAGE; i++) {
                page.addTargetRequest(channelUrl + "pg" + i);
            }
        }
    }

    @Override
    public Site getSite() {
        return site;
    }

    public void setChannelUrl(String channelUrl) {
        this.channelUrl = channelUrl;
    }

    public String getChannelUrl() {
        return channelUrl;
    }

    public static void main(String[] args) {
        Spider.create(new DataCrawlerProcessor())
                //从"链家网"开始抓
                .addUrl(CrawlerConstant.SH_LIAN_JIA_URL + "jingan/")
                //开启1个线程抓取
                .addPipeline(new DataPipeLine())
                .thread(1)
                .run();
    }
}
